package com.comm;

import com.dao.ISysLog;
import com.model.SysLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Order(5)
@Component
@Aspect
public class LogAopAspect {

    @Autowired
    private ISysLog iSysLog;

    @Around("@annotation(com.comm.LogAnno)")
    public Object auoundAd(ProceedingJoinPoint pjp){
        System.out.println("进入环形通知方法");
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Method method = methodSignature.getMethod();

        LogAnno logAnno = method.getAnnotation(LogAnno.class);
        String oper = logAnno.OperateType();

        SysLog sysLog = new SysLog();
        sysLog.setUserName("admin");
        sysLog.setOperation("接口描述" + oper);
        sysLog.setIp(HttpContextUtil.getIPAddress());

        String className = pjp.getTarget().getClass().getName();
        String methodName = methodSignature.getName();
        sysLog.setMethod(className + "." + methodName);

        Object[] args = pjp.getArgs();
        System.out.println("获取参数长度" + args.length);
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        String[] paramsNames = u.getParameterNames(method);
        System.out.println("方法中所涵盖的参数名称：" + paramsNames.length);
        if (args != null && paramsNames != null){
            String params = "";
            for (int i = 0; i < args.length; i++){
                params += " " + paramsNames[i] + ":" + args[i];
            }

            sysLog.setParams(params);
        }

        Object result = null;
        try {
            long begin = System.currentTimeMillis();
            try {
                result = pjp.proceed();
            } catch (Throwable e) {
                e.printStackTrace();
            }

            long end = System.currentTimeMillis();
            sysLog.setTime(end - begin);
            sysLog.setOperation("正常");
        } catch (Exception e) {
            sysLog.setOperation("失败");
        } finally {
            iSysLog.insertLog(sysLog);
            System.out.println("将访问接口的信息记录到数据库中");
        }
        System.out.println("结束环形通知方法");

        return result;
    }
}
